import wepy from 'wepy'
import constant from '../utils/constant.utils'
import { submitAuth } from '../utils/wx.login.utils'

const has = Object.prototype.hasOwnProperty
const getAuthSuccessCallback = function(that) {
  let method = has.call(that, method)
    ? method
    : has.call(that, 'onAuthSuccessFun')
    ? that['onAuthSuccessFun']
    : ''
  typeof that.onAuthSuccess === 'function' &&
    that.onAuthSuccess.call(that, method) &&
    console.log(that, method)
  has.call(that, '$com') &&
    Object.keys(that['$com']).length > 0 &&
    Object.values(that['$com']).forEach(that => {
      getAuthSuccessCallback(that)
    })
}

export default class AuthMixin extends wepy.mixin {
  methods = {
    auth(e) {
      // 在 wxml 上自定义的属性
      // data-method
      // data-args
      const { method, args } = e.currentTarget.dataset
      const detail = e.detail
      const errMsg = detail.errMsg
      // 取消、确认授权都会返回错误消息
      if (errMsg !== constant.WX.GET_USER_INFO) {
        return console.info('AuthMixin auth:', errMsg)
      }

      // 获取授权用户信息 userInfo
      const globalData = wx.$getGlobalData({ instance: this })
      globalData.userInfo = detail.userInfo
      console.info('userInfo:', globalData.userInfo)

      if (globalData.code !== '') {
        submitAuth({
          code: globalData.code,
          encryptData: detail.encryptedData,
          encryptIv: detail.iv
        }).then(
          response => {
            // 授权后更新用户授权状态
            this.setAuthStatus()
            // 执行当前授权后的回掉方法
            this[method] && this[method](args)
            // 执行授权成功方法
            getAuthSuccessCallback(this)
          },
          ({ data }) => {
            wx.$tips.toast(data.msg)
          }
        )
      } else {
        // 授权后更新用户授权状态
        this.setAuthStatus()
        this[method] && this[method](args)
        getAuthSuccessCallback(this)
      }
    }
  }
}
